﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using org.dicomcs.data;
using org.dicomcs.dict;
using log4net;
using System.Reflection;

namespace waveform_test.main
{
    public class LoadDcmFile
    {
        private static readonly ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private Stream ins = null;
        private DcmParser parser = null;
        private Dataset ds = null;
        private FileInfo file = null;

        public Stream Ins { get { return ins; } }
        public DcmParser Parser { get { return parser; } }
        public Dataset Ds { get { return ds; } }
        public FileInfo File { get { return file; } }

        public LoadDcmFile()
        {
        }

        [Obsolete("No usado", true)]
        public void Load(String fileName)
        {
            Load(new FileInfo(fileName));
        }

        public bool Load(FileInfo file)
        {
            this.file = file;

            bool retval = false;

            try
            {
                try
                {
                    ins = new BufferedStream(new FileStream(File.FullName, FileMode.Open, FileAccess.Read));
                    parser = new DcmParser(ins);
                    FileFormat format = parser.DetectFileFormat();
                    if (format != null)
                    {
                        ds = new Dataset();
                        parser.DcmHandler = ds.DcmHandler;
                        //parser.ParseDcmFile(format, Tags.PixelData);
                        parser.ParseDcmFile(format);

                        log.Info("Loaded File " + File.FullName + " Successfully");
                        retval = true;
                    }
                    else
                    {
                        log.Info(File.FullName + " Has no format");
                        retval = false;
                    }
                }
                catch (Exception e)
                {
                    log.Error("Unexpected Exception: " + e.Message, e);
                    retval = false;
                }
            }
            finally
            {
                if (ins != null)
                {
                    try
                    {
                        ins.Close();
                    }
                    catch (IOException)
                    {
                    }
                }
            }
            return retval;
        }
    }
}
